import { useReactive } from "ahooks";
import { useModel } from "umi";
import compress from "gql-compress";

const useStoreDepartmentToTree = () => {
    const { graphqlFetch } = useModel("global");

    const state = useReactive({
        loading: false,
        departments: [],
    });

    const loadStoreDepartmentsToTree = async ({ oiType, oiRoot }) => {
        let res = await graphqlFetch({
            query,
            variables: {
                oiType,
                oiRoot,
            },
        });
        let departments =
            res?.a?.nodes.map((item) => {
                return {
                    ...item,
                    id: item.oiUuid,
                    type: "department",
                    children: item.children.nodes.map((item) => ({
                        ...item,
                        id: item.reUuid,
                        type: "person",
                    })),
                };
            }) || [];
        return departments;
    };

    return { ...state, loadStoreDepartmentsToTree };
};

const query = compress(`query MyQuery($oiType: String!, $oiRoot: UUID!) {
    a: allOrganizationInstitutions(condition: { oiType: $oiType, oiRoot: $oiRoot }, orderBy: PY_NAME_ASC) {
        nodes {
            oiName
            asInfo
            maInfo
            oiPaid
            oiType
            oiUuid
            oiDesc
            children: organizationInstitutionsMembersByOiUuid {
                nodes {
                    reUuid
                    reType
                    oiUuid
                    staff: organizationStaffByOsUuid {
                        osUuid
                        osName
                        osRoge
                    }
                    position: organizationPositionByOpUuid {
                        opUuid
                        opName
                    }
                }
            }
        }
    }
}`);

export default useStoreDepartmentToTree;
